<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2021-08-30 11:30:13
 * @LastEditTime: 2021-08-30 11:30:13
 * @LastEditors: Please set LastEditors
 -->
 <style scoped>
    .headerBtn{
        text-align: left;
        margin: 10px 0;
    }
    .pageStyle{
        text-align:right;
        float:right;
    }
    .ivu-table-wrapper{
        overflow:visible
    }
    .pageStyleVm{
        text-align: right;
        margin-top: 10px;
    }
    table .ivu-poptip-confirm .ivu-poptip-body .ivu-icon{
        left: 11px
    }
    .position_i{
        position: relative;
        top: -1px;
        margin-right: 5px
    }
    .ivu-table-tip{
        overflow: hidden !important;
    }
    .starlet{
        color: red;
        position: absolute;
        left: -60px;
        font-size: 18px;
        line-height: 38px;
        font-weight: 800;
    }
    .zIndexStyleBtn{
        position:relative;
        z-index:55
    }
    ul li{
        list-style: none
    }
    ._dot{
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #f90;
        margin-right: 5px
    }
</style>
<template>
    <div>
        <div class="headerBtn">
            <Button type="primary" ghost @click='addTaskBtn' icon="md-add">创建任务</Button>
            <!-- <Poptip
                :confirm = true
                title="您确定要删除这些任务吗？"
                placement="right">
                <Button type="primary" class="zIndexStyleBtn"><Icon type="md-trash" :size="16" class="position_i"/>删除任务</Button>
            </Poptip> -->
            <!-- <Button type="primary"  class="zIndexStyleBtn"><Icon type="md-settings" :size="16" class="position_i"/>配置管理</Button> -->
            <Page :total="taskTotal"  show-sizer :current="pageIndex" :page-size="pageSize" :show-total= true  
            class-name="pageStyle" @on-change='changTaskList' @on-page-size-change='changeTaskPageSize' />
        </div>
        <Table border ref="selection" :columns="taskCol" :data="taskList"  :stripe="showStripe" :show-header="showHeader" :height="tableHeight"></Table>
        <Modal
            v-model="addTaskmodel"
            :title="linkModelTitle"
            :mask-closable="false"
            :footer-hide="true"
            width = '600'>
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="名称" prop="name">
                    <Input v-model="formValidate.name" :placeholder="nameErrorTipNotSC" clearable :maxlength="64"></Input>
                </FormItem>
                <FormItem style="text-align:right;">
                    <Button @click="resetBtn('formValidate')">取消</Button>
                    <Button style="margin-right: 10px;margin-left: 20px;" type="primary" @click="saveBtn('formValidate')" :loading="alliLoad">确定</Button>
                </FormItem>
            </Form>
        </Modal>
        <!-- 检测项管理 -->
        <Modal 
            v-model="testItemModel" 
            width='1000'
            title="检测项管理">
            <Button type="primary" class="zIndexStyleBtn" @click='addTestBtn'><Icon type="md-add-circle" :size="16" class="position_i"/>创建检测项</Button>
            <Table border :columns="checkCol" :data="allCheckItem"  :stripe="showStripe" :show-header="showHeader" style="margin-top: 15px;"></Table>
        </Modal>

        <!-- 添加/修改 检测项 -->
        <Modal 
            v-model="testModel" 
            width='600'
            :footer-hide="true"
            :title="checkTitle">
            <Form ref="formV" :model="formV" :rules="formVRule" :label-width="80">
                <FormItem label="配置类型" prop="conf">
                    <Select filterable v-model="formV.conf" placeholder="请选择配置类型" :disabled='!isCreatCheck'>
                        <Option value="access">接入</Option>
                        <Option value="reachable">网络可达</Option>
                        <Option value="scan">网络IP扫描</Option>
                        <Option value="port">开放端口</Option>
                    </Select>
                </FormItem>
                <!-- 虚拟机选择 -->
                <div v-if="formV.conf === 'access' || formV.conf === 'port'">
                    <FormItem v-model="formV.selectedVmData"  label="虚拟机" prop="selectedVmData">
                        <Tag v-for="item in formV.selectedVmData" :key="item.name" :name="item.id" closable @on-close="handleClose2" 
                        color="primary" type='dot' >{{ item.name }}</Tag>
                    </FormItem>
                    <div style="text-align:right">
                        <Button type="primary" @click="addSelectedData" style="margin-right:17px">添加</Button>
                        <Select filterable placeholder="子网" style="width: 149px" label-in-value filterable clearable @on-change="filterNetVm">
                            <Option  v-for="item in subnetList" :key="item.networkId" :value="item.networkId">{{item.networkName}}</Option>
                        </Select>
                        <Input placeholder="设备名称" style="width: 150px" v-model='vmName' clearable></Input>
                        <Input placeholder="搜索IP" style="width: 120px" v-model='vmIP' clearable></Input>
                        <Button type="primary" @click="refreshVmList" style="margin-left:5px">搜索</Button>
                    </div>
                    <Page :total="vmTotal" :current="vmCurrentPage" :page-size="vmItemPage" :show-total= true  show-sizer
                        @on-change="switchineVmCurrentPage" @on-page-size-change="switchVmItemPage" class-name="pageStyleVm"/>
                    <Table border :columns="columnsVmList" :data="dataVmList"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" 
                        style="margin:16px 0"  @on-selection-change="getSelectedData"></Table>
                </div>
                <!-- 端口 -->
                <div style="margin-top: 16px;" v-if="formV.conf === 'port'">
                    <FormItem v-model="formV.port"  label="已加端口" prop="port">
                        <Tag v-for="item in formV.port" :key="item" :name="item" closable @on-close="handleClose3" 
                        color="primary" type='dot' >{{ item }}</Tag>
                    </FormItem>
                    <FormItem label="添加端口">
                        <Input v-model="port" placeholder="端口范围:0-65535" style="width: 180px;"></Input>
                        <Button type="primary" style="margin-left:17px" @click='addPort'>添加</Button>
                    </FormItem>
                </div>
                <!-- 子网 -->
                <div >
                    <FormItem :label="formV.conf === 'reachable'?'源子网':'子网'" prop="subnetId" v-if="formV.conf === 'reachable' || formV.conf === 'scan'">
                        <Select filterable v-model="formV.subnetId" placeholder="源子网" >
                            <Option  v-for="item in subnets" :key="item.id" :value="item.id">{{item.name}}</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="目的" prop="target" v-if="formV.conf === 'reachable'">
                        <Input v-model="formV.target" placeholder="目的子网cidr/目的ip/目的ip范围(10.1.1.10-20)" :maxlength="64"></Input>
                    </FormItem>
                </div>
                <FormItem style="text-align:right;">
                    <Button  @click="resetBtn('formV')">取消</Button>
                    <Button style="margin-left: 10px;" type="primary" @click="subBtn('formV')" :disabled="checkLoading" :loading='checkLoading'>确定</Button>
                    <!-- ddd -->
                </FormItem>
            </Form>
        </Modal>
        <!-- 查看检测项结果 -->
        <Modal 
            v-model="testResultModel" 
            width='1000'
            title="检测详情">
            <Table border :columns="testResultCol" :data="testResultData"  :stripe="showStripe" :show-header="showHeader" style="margin-top: 15px;"></Table>
        </Modal>
    </div>
</template>
<script>
    import axios from '@/libs/axios1'
    import {validateNameCNLU,taskMixin } from './taskMixin'
    // const validateNameCNLU = (rule, value, callback) => {
    //     var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
    //     value = value.replace(/\s*/g,"");
    //     if(!value){
    //         callback("请填写名称");
    //     }else{
    //         if (myReg.test(value)) {
    //             callback("名称不能包含特殊字符");
    //         } else {
    //             callback();
    //         }
    //     }
    // };
    export default {
        name:"linkCheck",
        props:['sceneId','projectId'],
        mixins:[taskMixin],
        data(){
            const validateVm = (rule, value, callback) => {
                if(value.length > 0){
                    callback();
                }else {
                    callback(new Error('请选择虚拟机'));
                }
            };
            const validatePort = (rule, value, callback) => {
                if(value.length > 0){
                    callback();
                }else {
                    callback(new Error('请添加端口'));
                }
            };
            return{
                tableHeight:'',
                taskConfigerMess:false,
                // projectId:"",
                // sceneId:'',
                // 任务列表
                showStripe: true,
                showHeader:true,
                taskList:[],
                taskCol:[
                    {
                        type: 'index',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title: '任务名称',
                        key: 'name',
                        align:'center',
                        tooltip:true
                    },
                    {
                        title: '任务状态',
                        key: 'status',
                        align:'center',
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.status == 'init'){
                                text = '初始化'
                            }else if(params.row.status == 'complated'){
                                text = '已完成'
                            }else if(params.row.status == 'running'){
                                text = '进行中'
                            }
                            return h('span',text)
                        }
                    },
                    {
                        title: '检测项',
                        key: 'status',
                        align:'center',
                        render:((h,params)=>{
                            return h('Button', {
                                props: {
                                    type:'primary',
                                    size:'small'
                                },
                                on: {
                                    'click': ()=>{
                                        this.testItemBtn(params.row)
                                    },
                                }
                            },'检测项')
                        })
                    },
                    {
                        title: '创建人',
                        key: 'creatorName',
                        align:'center'
                    },
                    {
                        title: '创建时间',
                        key: 'created',
                        align:'center'
                    },
                    {
                        title: '操作',
                        key: 'optation',
                        align:'center',
                        width:300,
                        render:((h,params)=>{
                            let text = '开始'
                            let status = 'success'
                            if(params.row.status === 'init'){
                                text = '开始'
                                status = 'success'
                            }else if(params.row.status === 'running'){
                                text = '停止'
                                status = 'error'
                            }
                            return h('a',{
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'center',
                                    'align-items': 'center',
                                    color:'#2f70ff'
                                },
                            },[
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: '确定要删除吗？'
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.delTaskBtn(params.row.id)
                                            },
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type:'error',
                                                size:'small'
                                            },
                                        },'删除任务'),
                                    ],
                                ),
                                h('Button', {
                                    props: {
                                        type:'primary',
                                        size:'small'
                                    },
                                    style:{
                                        'margin':'0 10px'
                                    },
                                    on: {
                                        'click': ()=>{
                                            this.modifyTaskBtn(params.row)
                                        },
                                    }
                                },'修改任务'),
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: `确定要${text}吗？`
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.startTask(params.row)
                                            },
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type:status,
                                                size:'small'
                                            },
                                        },text+'任务'),
                                    ],
                                ),
                            ])
                        })
                    },
                ],
                taskTotal:0,
                pageIndex:1,
                pageSize:10,
                midStatusArr:[],
                taskSetInterval:null,
                // 添加任务
                isCreat:true,
                addTaskmodel:false,
                alliLoad:false,
                formValidate:{
                    name:'',
                },
                ruleValidate:{
                    name: [
                        { required: true, message: '名称不能为空', trigger: 'blur',validator:validateNameCNLU }
                    ],
                },
                // 修改任务
                modifyTaskId:'',
                // 检测项
                openItemIndex:0,  // 当前打开的检测项索引
                testItemTaskId:'',
                allCheckItem:[],
                testItemModel:false,
                checkCol:[
                    {
                        type: 'index',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title:'检测类型',
                        key:'type',
                        align:'center',
                        render: (h, params) => {
                            let text = ''
                            if(params.row.type === 'access'){
                                text = '接入'
                            }else if(params.row.type === 'network_reachable'){
                                text = '网络可达'
                            }else if(params.row.type === 'network_scan'){
                                text = '网络IP扫描'
                            }else if(params.row.type === 'open_port'){
                                text = '开放端口'
                            }
                            return h('div',text)
                        }
                    },
                    {
                        title:'检测状态',
                        key:'status',
                        align:'center',
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.status == 'init'){
                                text = '初始化'
                            }else if(params.row.status == 'running'){
                                text = '进行中'
                            }else if(params.row.status == 'complete'){
                                text = '已完成'
                            }
                            return h('span',text)
                        }
                    },
                    {
                        title:'检测结果',
                        key:'result',
                        align:'center',
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.result == 'pass'){
                                text = '通过'
                            }else if(params.row.result == 'fail'){
                                text = '失败'
                            }
                            return h('span',text)
                        }
                    },
                    {
                        title:'检测详情',
                        key:'result',
                        align:'center',
                        render:(h,params)=>{
                            if(params.row.status != 'init'){
                                return h('Button',{
                                    on: {
                                        'click': ()=>{
                                            this.showResult(params.row)
                                        },
                                    }
                                },'查看详情')
                            }else{
                                return h('div','-')
                            }
                        }
                    },
                    {
                        title: '操作',
                        key: 'optation',
                        align:'center',
                        render:((h,params)=>{
                            return h('a',{
                                style: {
                                    'display': 'flex',
                                    'justify-content': 'center',
                                    'align-items': 'center',
                                    color:'#2f70ff'
                                },
                            },[
                                h('Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            transfer:true,
                                            title: '确定要删除吗？'
                                        },
                                        on: {
                                            'on-ok': ()=>{
                                                this.delCheckBtn(params.row)
                                            },
                                        }
                                    },
                                    [
                                        h('Button', {
                                            props: {
                                                type:'error'
                                            },
                                            style:{
                                                'margin-right':'10px'
                                            },
                                        },'删除'),
                                    ],
                                ),
                                h('Button', {
                                    props: {
                                        type:'primary'
                                    },
                                    on: {
                                        'click': ()=>{
                                            this.modifyCheckBtn(params.row)
                                        },
                                    }
                                },'修改检测项')
                            ])
                        })
                    },
                ],
                // 添加检测项
                checkTitle:'创建检测项',
                linkModelTitle:'创建任务',
                isCreatCheck:true,
                checkLoading:false,
                port:0,
                testModel:false,
                modifyCheckItemIndex:0, 
                formV:{
                    conf:'access',
                    selectedVmData:[],
                    subnetId:'',
                    target:'',
                    port:[],
                },
                formVRule:{
                    conf: [
                        { required: true, message: '请选择配置项类型', trigger: 'chang' }
                    ],
                    subnetId: [
                        { required: true, message: '请选择源子网', trigger: 'change' }
                    ],
                    target: [
                        { required: true, message: '请选择目的', trigger: 'blur' }
                    ],
                    selectedVmData: [
                        { required: true,validator: validateVm, trigger: 'change' },
                    ],
                    port: [
                        { required: true,validator: validatePort, trigger: 'change' },
                    ],
                },
                // 查看执行结果
                testResultModel:false,
                testResultData:[],
                testResultCol:[],
                // 虚拟机列表
                showStripe:true,
                showHeader:true,
                tableSize: 'small',
                dataVmList:[],
                networkId:'',
                vmName:'',
                vmIP:'',
                vmTotal:0,
                vmCurrentPage:1,
                vmItemPage:10,
                selectedDataConfiger:[],
                selectedVmDataTable:[],
                columnsVmList:[
                    {
                        type:'selection',
                        width:60,
                        align:'center'
                    },
                    {
                        title:'设备名称',
                        key:'name',
                        align:'center'
                    },
                    {
                        title:'IP',
                        key:'IP',
                        align:'center',
                        render:(h,params)=>{
                            let value = params.row.IP;
                            let oIP_ = [];
                            value.forEach((item,i)=>{
                                oIP_.push(h("p",{
                                    color:'#000',
                                },item))
                            })
                            return h("div",oIP_)
                        }
                    },
                    {
                        title:'网络名称',
                        key:'networkName',
                        align:'center'
                    },
                    {
                        title:'添加',
                        key:'add',
                        align:'center',
                        render:(h,params) =>{
                            let _this = params;
                            return h('Button', {
                                props: {
                                    type: 'primary',
                                },
                                on:{
                                    click: (e) => {
                                        if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                            this.$Message.info("已添加")
                                            return;
                                        }
                                        this.addVmAfterTable(_this.row)
                                        this.selectedVmDataTable.push(_this.row.id)
                                        this.formV.selectedVmData.push({
                                            "name":_this.row.name,
                                            "id":_this.row.id
                                        })
                                    },
                                }
                            }, "+");
                        }
                    }
                ],
                subnetList:[],
                // 获取已部署工程的子网列表
                subnets:[],
                modifyItemId:'',
                vmObjData:{},// 存个虚拟机字典
            }
        },
        created(){
            // this.projectId = this.$route.query.projectId
            // this.sceneId = this.$route.query.sceneId || this.sceneId
            // this.tableHeight = $(window).height() - 224 ;
        },
        mounted(){
            // 任务列表
            this.getLinkTaskList()
        },
        beforeDestroy(){
            clearInterval(this.taskSetInterval)
        },
        methods: {
            // 任务列表
            getLinkTaskList(){
                let params = {
                    pageIndex:this.pageIndex,
                    pageSize:this.pageSize,
                    order:'desc',
                    projectId:this.projectId,
                }
                this.midStatusArr = []
                clearInterval(this.taskSetInterval)
                axios({
                    url:'topo-edit/network_checking/tasks',
                    method:'get',
                    params:params
                }).then((res)=>{
                    if (res.code==1) {
                        if(res.code === 1){
                            let items = res.data.items
                            this.taskList = items
                            this.taskTotal = res.data.total
                            for(let i=0;i<items.length;i++){
                                if(items[i].status === 'running'){
                                    this.midStatusArr.push(items[i].id)
                                }
                            }
                            if(this.midStatusArr.length > 0){
                                // 轮询中间状态的工程
                                this.initQueryTaskState()
                            }
                        }
                    }
                })
            },
            changTaskList(val){
                this.pageIndex = val
                this.getLinkTaskList()
            },
            changeTaskPageSize(val){
                this.pageIndex = 1
                this.pageSize = val
                this.getLinkTaskList()
            },
            // 轮询任务列表
            initQueryTaskState(){
                this.taskSetInterval = setInterval(()=>{
                    let params = {
                        pageIndex:this.pageIndex,
                        pageSize:this.pageSize,
                        order:'desc',
                        projectId:this.projectId,
                    }
                    axios({
                        url:'topo-edit/network_checking/tasks',
                        method:'get',
                        params:params
                    }).then((res)=>{
                        if (res.code==1) {
                            if(res.code === 1){
                                let items = res.data.items
                                this.taskList = items
                                this.taskTotal = res.data.total
                                let arr = []
                                for(let i=0;i<items.length;i++){
                                    if(items[i].status === 'running'){
                                        arr.push(items[i].id)
                                    }
                                }
                                if(arr.length == 0){
                                    clearInterval(this.taskSetInterval)
                                }
                            }else{
                                clearInterval(this.taskSetInterval)
                            }
                        }
                    })
                },3000)
            },
            // 任务添加按钮
            addTaskBtn(){
                this.addTaskmodel = true
                this.isCreat = true
                this.formValidate.name = ''
                this.linkModelTitle = '创建任务'
            },
            resetBtn(name){
                this.$refs[name].resetFields();
                this.addTaskmodel = false
                this.testModel = false
            },
            saveBtn(name){
                if(this.isCreat){
                    this.subCreatTask(name)
                } else{
                    this.subModify(name)
                }
            },
            subCreatTask(name){
              
                let $this = this;
                $this.$refs[name].validate((valid) => {
                    if (valid) {
                        let params = {
                            name:this.formValidate.name,
                            projectId:this.projectId,
                        }
                        this.alliLoad = true
                        axios({
                            url:'topo-edit/network_checking/tasks',
                            method:'post',
                            data:params
                        }).then((res)=>{
                            if (res.code==1) {
                                this.$Message.success({
                                    content:'创建成功',
                                    duration:3
                                })
                                this.addTaskmodel = false
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.alliLoad = false
                        })
                    } else {
                        this.checkLoading = false;
                        $this.$Message.error('请完善信息')
                    }
                });
            },
            // 修改任务
            modifyTaskBtn(row){
                this.modifyTaskId = row.id
                this.addTaskmodel = true
                this.isCreat = false
                this.formValidate.name = row.name
                this.linkModelTitle = '修改任务'
            },
            subModify(name){
               
                let $this = this;
                $this.$refs[name].validate((valid) => {
                    if (valid) {
                        let params = {
                            name:this.formValidate.name,
                            projectId:this.projectId,
                        }
                        this.alliLoad = true
                        axios({
                            url:`topo-edit/network_checking/tasks/${this.modifyTaskId}`,
                            method:'put',
                            data:params
                        }).then((res)=>{
                            if (res.code==1) {
                                this.$Message.success({
                                    content:'修改成功',
                                    duration:3
                                })
                                this.addTaskmodel = false
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.alliLoad = false
                        })
                    } else {
                        this.checkLoading = false;
                        $this.$Message.error('请完善信息')
                    }
                });
            },
            // 删除任务
            delTaskBtn(id){
                axios({
                    url:`topo-edit/network_checking/tasks/${id}`,
                    method:'delete',
                }).then((res)=>{
                    if (res.code==1) {
                        this.$Message.success({
                            content:'删除成功',
                            duration:3
                        })
                        this.pageIndex = 1
                        this.getLinkTaskList()
                    }else{
                        this.$Message.error({
                            content:res.message,
                            duration:5,
                        })
                    }
                })
            },
            // 检测项
            testItemBtn(row){
                this.getVmList()
                this.getSubnetList()
                this.getSubnets()
                this.allCheckItem = row.items
                this.openItemIndex = row._index
                this.testItemTaskId = row.id
                this.testItemModel = true
            },
            // 添加检测项
            addTestBtn(){
                let $this = this
                this.formV = {
                    conf:'access',
                    selectedVmData:[],
                    subnetId:'',
                    target:'',
                    port:[],
                }
                this.isCreatCheck = true
                this.networkId = ''
                this.vmName = ''
                this.vmIP = ''
                this.vmCurrentPage = 1
                this.port = 0
                this.checkTitle = '创建检测项'
                this.testModel = true
                this.getVmList()
                $this.selectedVmDataTable = []
                this.dataVmList.forEach(function(item,i){
                    item._checked = false;
                    item._disabled = false;
                })
            },
            getSelectedData(selection){
                this.selectedDataConfiger = [];
                this.selectedDataConfiger = selection;
            },
            getVmList(){
                let $this = this;
                let data = {
                    pageIndex: this.vmCurrentPage,
                    pageSize: this.vmItemPage,
                    order: 'asc',
                    sortBy: 'name',
                }
                if(this.networkId != ''){
                    data.networkId = this.networkId
                }
                if(this.vmName){
                    data.name = this.vmName
                }
                if(this.vmIP){
                    data.ipAddress = this.vmIP
                }
                // $this.formV.selectedVmData = []
                axios({
                    url:`topo-edit/deployed/projects/${this.projectId}/vms`,
                    method:'get',
                    params:data
                })
                .then((response)=>{
                    $this.dataVmList = [];
                    if(response.code==1){
                        let vmData = response.data.items;
                        $this.vmTotal = Number(response.data.total);
                        let disabled_ = false;
                        let checked_ = false;
                        vmData.forEach(function(item,i){
                            $this.vmObjData[item.id] = item.name
                            if($this.selectedVmDataTable.length!=0){
                                if($this.selectedVmDataTable.indexOf(item.id)!=-1){
                                    disabled_ = true
                                    checked_ = true
                                }else{
                                    disabled_ = false
                                    checked_ = false
                                }
                            }else{
                                disabled_ = false
                                checked_ = false
                            }
                            let IPS = [];
                            if(item.addresses&&item.addresses.length!=0){
                                for(let i=0;i<item.addresses.length;i++){
                                    if(item.addresses[i].ips&&item.addresses[i].ips.length!=0){
                                        for (let index = 0; index < item.addresses[i].ips.length; index++) {
                                            const element = item.addresses[i].ips[index];
                                            IPS.push(element.ipAddress);
                                        }
                                    }
                                }
                            }
                            $this.dataVmList.push({
                                name:item.name,
                                id:item.id,
                                IP:IPS,
                                networkName:item.networkName,
                                _disabled: disabled_,
                                _checked:checked_,
                            })
                            // if($this.selectedVmDataTable.indexOf(item.id) > -1){  // 会导致切换分页时重复添加数据
                            //     $this.formV.selectedVmData.push({
                            //         name:item.name,
                            //         id:item.id,
                            //         IP:IPS,
                            //         _disabled: false,
                            //         _checked:true,
                            //     })
                            // }
                        })
                    }
                })
            },
            switchineVmCurrentPage(numberPage){
                this.vmCurrentPage = numberPage;
                this.getVmList()
            },
            switchVmItemPage(numberSize){
                this.vmCurrentPage = 1
                this.vmItemPage = numberSize
                this.getVmList()
            },
            addSelectedData(){
                let that = this,bol = true;
                that.selectedDataConfiger.forEach(function(item,i){
                    if(that.selectedVmDataTable.indexOf(item.id)!=-1){
                        
                    }else{
                        bol = false
                        that.addVmAfterTable(item)
                        that.selectedVmDataTable.push(item.id)
                        that.formV.selectedVmData.push({
                            "name":item.name,
                            "id":item.id
                        })
                    }
                })
                if(bol){
                    that.$Message.info("请选择要添加的内容")
                }
            },
            addVmAfterTable(param){
                let data = this.dataVmList;
                this.dataVmList.forEach(function(item,i){
                    if(item.id==param.id){
                        item._checked = true;
                        item._disabled = true;
                    }
                })
            },
            refreshVmList(){
                this.vmCurrentPage = 1
                this.getVmList()
            },
            // 获取子网络列表
            getSubnetList(){
                let _this = this;
                axios({
                    url:`topo-edit/topo/project/${this.projectId}/tree?types=NW`,
                    method:'get',
                })
                .then(res=>{
                    if(res.code === 1){
                        _this.subnetList = [];
                        let networkDataTree = res.data;
                        function getNetwork(currentNetworkData){
                            // if(currentNetworkData.name!="rootNetwork"){
                                _this.subnetList.push({
                                    networkName:currentNetworkData.name,
                                    networkId:currentNetworkData.id
                                })
                            // }
                            if(currentNetworkData.networks&&currentNetworkData.networks.length!=0){
                                for(let i = 0;i<currentNetworkData.networks.length;i++){
                                    getNetwork(currentNetworkData.networks[i])
                                }
                            }
                        }
                        getNetwork(networkDataTree)
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            getSubnets(){
                axios({
                    url:`topo-edit/deployed/projects/${this.projectId}/subnets?projectId=${this.projectId}`,
                    method:'get',
                })
                .then(res=>{
                    if(res.code === 1){
                       this.subnets = res.data.items
                    }
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            filterNetVm(val){
                if(val){
                    this.networkId = val.value
                }else{
                    this.networkId = ''
                }
                this.getVmList()
            },
            handleClose2 (event, name) {
                let $this = this;
                let data = this.formV.selectedVmData;
                $this.selectedDataConfiger= [];
                let _data = this.selectedVmDataTable;
                data.forEach(function(item,i){
                    if(item){
                        if(item.id==name){
                            data.splice(i,1);
                            _data.splice(_data.findIndex(item => item === name), 1)
                            $this.judgeVmStatus(name)
                        }
                    }
                });
            },
            handleClose3(event, name){
                let $this = this;
                let data = this.formV.port;
                data.forEach(function(item,i){
                    if(item === name){
                        data.splice(i,1);
                    }
                });
            },
            judgeVmStatus(name){
                let data = this.dataVmList;
                let data_ = this.selectedVmDataTable
                data.forEach(function(item,i){
                    if(item.id==name){
                        item._checked = false;
                        item._disabled = false;
                    }
                })
            },
            addPort(){
                let port = parseInt(this.port)
                if(port >=0 && port <= 65535){
                    if(this.formV.port.indexOf(port) > -1){
                        this.$Message.warning('该端口已添加，请勿重复添加!')
                    }else{
                        this.formV.port.push(port)
                    }
                    this.port = ''
                }else{
                    this.$Message.error('端口填写错误!')
                }
            },
            // 提交检测项
            subBtn(name){
                this.checkLoading = true;
                if(this.isCreatCheck){  // 新建
                    if(this.formV.conf === 'access'){
                        this.creatAccess(name)
                    }else if(this.formV.conf === 'reachable'){
                        this.creatReachable(name)
                    }else if(this.formV.conf === 'scan'){
                        this.creatScan(name)
                    }else if(this.formV.conf === 'port'){
                        this.creatPort(name)
                    }
                }else{ // 修改
                    if(this.formV.conf === 'access'){
                        this.modifyAccess(name)
                    }else if(this.formV.conf === 'reachable'){
                        this.modifyReachable(name)
                    }else if(this.formV.conf === 'scan'){
                        this.modifyScan(name)
                    }else if(this.formV.conf === 'port'){
                        this.modifyPort(name)
                    }
                }   
            },
            creatAccess(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            deviceIds:this.selectedVmDataTable
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/access?taskId=${this.testItemTaskId}`,
                            method:'post',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                this.allCheckItem.push(res.data)
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3
                                })
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            creatReachable(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            subnetId:this.formV.subnetId,
                            target:this.formV.target
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/network_reachable?taskId=${this.testItemTaskId}`,
                            method:'post',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                this.allCheckItem.push(res.data)
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3
                                })
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            creatScan(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            subnetId:this.formV.subnetId,
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/network_scan?taskId=${this.testItemTaskId}`,
                            method:'post',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                this.allCheckItem.push(res.data)
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3
                                })
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            creatPort(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            deviceIds:this.selectedVmDataTable,
                            ports:this.formV.port,
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/open_port?taskId=${this.testItemTaskId}`,
                            method:'post',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                this.allCheckItem.push(res.data)
                                this.$Message.success({
                                    content:'添加成功',
                                    duration:3
                                })
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            // 修改检测项
            modifyCheckBtn(row){
                console.log(row)
                this.modifyItemId = row.id
                this.formV = {
                    conf:'access',
                    selectedVmData:[],
                    subnetId:'',
                    target:'',
                    port:[], 
                }
                this.vmCurrentPage = 1
                this.networkId = ''
                this.vmName = ''
                this.vmIP = ''
                this.port = 0
                this.isCreatCheck = false
                this.checkTitle = '修改检测项'
                this.modifyCheckItemIndex = row._index
                this.selectedVmDataTable = []
                if(row.type === 'access'){
                    this.formV.conf = 'access'
                    this.selectedVmDataTable = row.metadata.deviceIds
                    this.huixianVm(row.metadata.deviceIds)
                }else if(row.type === 'network_reachable'){
                    this.formV.conf = 'reachable'
                    this.formV.subnetId = row.metadata.subnetId
                    this.formV.target = row.metadata.target
                }else if(row.type === 'network_scan'){
                    this.formV.conf = 'scan'
                    this.formV.subnetId = row.metadata.subnetId
                }else if(row.type === 'open_port'){
                    this.formV.conf = 'port'
                    this.selectedVmDataTable = JSON.parse(JSON.stringify(row.metadata.deviceIds))
                    this.formV.port = JSON.parse(JSON.stringify(row.metadata.ports))
                    this.huixianVm(row.metadata.deviceIds)
                }
                this.getVmList()
                this.testModel = true
            },
            huixianVm(arr){
                let $this = this
                this.dataVmList.forEach(function(item,i){
                    item._checked = false;
                    item._disabled = false;
                    if(arr.indexOf(item.id) > -1){
                        item._checked = true;
                        item._disabled = false;
                        $this.formV.selectedVmData.push({
                            name:item.name,
                            id:item.id,
                        })
                    }
                })
            },
            modifyAccess(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            deviceIds:this.selectedVmDataTable
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/${this.modifyItemId}/access`,
                            method:'put',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                // this.allCheckItem[this.modifyCheckItemIndex] = res.data
                                this.$Message.success({
                                    content:'修改成功',
                                    duration:3
                                })
                                this.testItemModel = false;
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            modifyReachable(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            subnetId:this.formV.subnetId,
                            target:this.formV.target
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/${this.modifyItemId}/network_reachable`,
                            method:'put',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                // this.allCheckItem[this.modifyCheckItemIndex] = res.data
                                this.$Message.success({
                                    content:'修改成功',
                                    duration:3
                                })
                                this.testItemModel = false;
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            modifyScan(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            subnetId:this.formV.subnetId,
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/${this.modifyItemId}/network_scan`,
                            method:'put',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                // this.allCheckItem[this.modifyCheckItemIndex] = res.data
                                this.$Message.success({
                                    content:'修改成功',
                                    duration:3
                                })
                                this.testItemModel = false;
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            modifyPort(name){
                this.$refs[name].validate((valid) => {
                    if (valid){
                        let data = {
                            deviceIds:this.selectedVmDataTable,
                            ports:this.formV.port,
                        }
                        this.checkLoading = true
                        axios({
                            url:`topo-edit/network_checking/items/${this.modifyItemId}/open_port`,
                            method:'put',
                            data:data,
                        }).then((res)=>{
                            if (res.code==1) {
                                this.testModel = false
                                // this.allCheckItem[this.modifyCheckItemIndex] = res.data
                                this.$Message.success({
                                    content:'修改成功',
                                    duration:3
                                })
                                this.testItemModel = false;
                                this.getLinkTaskList()
                            }else{
                                this.$Message.error({
                                    content:res.message,
                                    duration:5,
                                })
                            }
                            this.checkLoading = false
                        })
                    } else {
                        this.checkLoading = false;
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            delCheckBtn(row){
                let _index = row._index
                axios({
                    url:`topo-edit/network_checking/items/${row.id}`,
                    method:'delete',
                }).then((res)=>{
                    if (res.code==1) {
                        this.allCheckItem.splice(_index,1)
                        this.$Message.success({
                            content:'删除成功',
                            duration:3
                        })
                        this.getLinkTaskList()
                    }else{
                        this.$Message.error({
                            content:res.message,
                            duration:5,
                        })
                    }
                })
            },
            // 任务启动
            startTask(row){
                if(row.items.length == 0){
                    this.$Message.warning('当前无检测项，请配置检测项')
                    return false
                }
                if(row.status === 'init' || row.status === 'complated'){  // 调用开始任务
                    this.implementTask(row.id,'start')
                }else if(row.status === 'running'){  // 调用停止任务
                    this.implementTask(row.id,'stop')
                }
            },
            implementTask(id,type){
                axios({
                    url:`topo-edit/network_checking/tasks/${id}/${type}`,
                    method:'post',
                }).then((res)=>{
                    if (res.code==1) {
                        this.$Message.success({
                            content:'成功',
                            duration:3
                        })
                        this.getLinkTaskList()
                    }else{
                        this.$Message.error({
                            content:res.message,
                            duration:5,
                        })
                    }
                })
            },
            // 查看检测结果
            showResult(row){
                this.testResultData = []
                this.testResultCol = []
                this.testResultCol.push({
                    type:'index',
                    width:60,
                    align:'center'
                })
                axios({
                    url:`topo-edit/network_checking/items/${row.id}/detail`,
                    method:'get',
                }).then((res)=>{
                    if (res.code==1) {
                        if(res.data.type === 'access'){  // 接入
                            let deviceIds = res.data.metadata.deviceIds
                            let nameArr = []
                            for(let i=0;i<deviceIds.length;i++){
                                nameArr.push(this.vmObjData[deviceIds[i]])
                            }
                            res.data.nameStr = nameArr.join(',')
                            this.testResultCol.push({
                                title:'设备名称',
                                key:'nameStr',
                                align:'center'
                            })
                        }else if(res.data.type === 'network_reachable'){ // 网络可达
                            res.data.mbIP = res.data.metadata.target
                            this.testResultCol.push({
                                title:'目标IP',
                                key:'mbIP',
                                align:'center'
                            })
                        }else if(res.data.type === 'open_port'){  // 开放端口
                            let deviceIds = res.data.metadata.deviceIds
                            let nameArr = []
                            for(let i=0;i<deviceIds.length;i++){
                                nameArr.push(this.vmObjData[deviceIds[i]])
                            }
                            res.data.nameStr = nameArr.join(',')
                            res.data.openduan = res.data.metadata.ports.join(',')
                            this.testResultCol.push(
                                {
                                    title:'设备名称',
                                    key:'nameStr',
                                    align:'center'
                                },
                                {
                                    title:'端口',
                                    key:'openduan',
                                    align:'center'
                                },
                            )
                        }else if(res.data.type === 'network_scan'){ // 网络IP扫描
                            let details = res.data.details
                            let ipArr = []
                            for(let i=0;i<details.length;i++){
                                ipArr.push(details[i].value)
                            }
                            res.data.ipArr = ipArr.join(',')
                            this.testResultCol.push(
                                {
                                    title:'扫描IP',
                                    key:'ipArr',
                                    align:'center'
                                },
                            )
                        }
                        this.testResultCol.push({
                            title:'信息',
                            key:'errmsg',
                            align:'center',
                            render:(h,params)=>{
                                let text = '通过'
                                if(params.row.errmsg){
                                    text = params.row.errmsg
                                }else if(params.row.msg){
                                    text = params.row.msg
                                }
                                return h('span',text)
                            }
                        })
                        this.testResultData.push(res.data)
                        this.testResultModel = true
                    }else{
                        this.testResultData = []
                        this.$Message.error({
                            content:res.message,
                            duration:5,
                        })
                    }
                })
            },
            // 接入的连通结果

        },
        watch:{
            
        }
    }
</script>
    
    
    